package org.aaron.demos;

import android.app.Activity;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class ProgressActivity extends Activity {

	private static final int PROGRESS = 0x0;
	private int mProgressStatus = 0;
	private ProgressBar firstProgressBar;
	private ProgressBar secendProgressBar;
	private Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.progresslayout);
		initActivity();
	}

	private void initActivity() {
		firstProgressBar = (ProgressBar) this.findViewById(R.id.firstProgress);
		secendProgressBar = (ProgressBar) this.findViewById(R.id.secendProgress);
		button = (Button) this.findViewById(R.id.proressBtn);
		button.setOnClickListener(new HandleButtonClickListener());

	}

	private class ButtonClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (PROGRESS == mProgressStatus) {
				firstProgressBar.setVisibility(View.VISIBLE);
				secendProgressBar.setVisibility(View.VISIBLE);
			} else if (mProgressStatus < 100) {
				firstProgressBar.setProgress(mProgressStatus);
				firstProgressBar.setSecondaryProgress(mProgressStatus + 10);
				secendProgressBar.setProgress(mProgressStatus);
			} else {
				firstProgressBar.setVisibility(View.GONE);
				secendProgressBar.setVisibility(View.GONE);
			}
			mProgressStatus = mProgressStatus + 10;
		}

	}

	private class HandleButtonClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			firstProgressBar.setVisibility(View.VISIBLE);
			handler.post(runnable);
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			firstProgressBar.setProgress(msg.arg1);
			handler.post(runnable);
		}
	};

	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			System.out.println("Runnale Runing!");
			mProgressStatus+=10;
			Message message=handler.obtainMessage();
			message.arg1=mProgressStatus;
			try {
				Thread.sleep(1000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			handler.sendMessage(message);
			if(firstProgressBar.getMax()<=mProgressStatus){
				handler.removeCallbacks(runnable);
				firstProgressBar.setVisibility(View.GONE);
			}
		}
	};
}
